package org.example.platform.elasticsearch.client;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class EsClient {
    @Value("${elasticsearch.rest.hosts}")
    private String hosts;

    //配置高级客户端
    @Bean(name = "client")
    public RestHighLevelClient initSimpleClient() {
        HttpHost[] httpHosts = Arrays.stream(hosts.split(",")).map(
                host -> {
                    String[] hostParts = host.split(":");
                    String hostName = hostParts[0];
                    int port = Integer.parseInt(hostParts[1]);
                    return new HttpHost(hostName, port, HttpHost.DEFAULT_SCHEME_NAME);
                }).toArray(HttpHost[]::new);
        //返回客户端
        return new RestHighLevelClient(RestClient.builder(httpHosts));
    }
}
